Error reported by Custom loss function

Traceback (most recent call last):
File “F:\pythonProject\DG\main.py”, line 178, in
model.compile(loss=loss_n,
File “C:\Users\86133\anaconda3\lib\site-packages\keras\utils\traceback_utils.py”, line 67, in error_handler
raise e.with_traceback(filtered_tb) from None
File “C:\Users\86133\anaconda3\lib\site-packages\keras\engine\keras_tensor.py”, line 221, in len
raise TypeError('Keras symbolic inputs/outputs do not ’
TypeError: Keras symbolic inputs/outputs do not implement __len__. You may be trying to pass Keras symbolic inputs/outputs to a TF API that does not register dispatching, preventing Keras from automatically converting the API call to a lambda layer in the Functional Model. This error will also get raised if you try asserting a symbolic input/output directly.

Process finished with exit code 1

@zheng_joe,

Welcome to the Tensorflow Forum!

Could you please share a standalone code to replicate issue reported here?

Thank you!

Thank you in advance. The code is as follows

def Net(inputs):
x = tf.keras.layers.Conv2D(filters=5, kernel_size=3, strides=2, padding=‘same’)(inputs)
x = tf.keras.activations.relu(x)
x = tf.keras.layers.BatchNormalization()(x)
x = tf.keras.layers.MaxPooling2D(pool_size=5, strides=2, padding=‘same’)(x)
x = tf.keras.layers.GlobalAveragePooling2D()(x)
x = tf.keras.layers.Dropout(0.5)(x)
H = tf.keras.layers.Dense(64)(x)
logits = tf.keras.layers.Dense(12)(H)
pred = tf.keras.activations.softmax(logits)
return pred, H, logits

def loss_function(H,logits):
Lc = tf.compat.v1.losses.softmax_cross_entropy(label_train, logits)
batch_size =32
norm = lambda x: tf.reduce_sum(tf.square(x), 1)
F0 = tf.transpose(norm(tf.expand_dims(H, 2) - tf.transpose(H)))
margin0 = 0.0
margin1 = 100.0
F0 = tf.pow(tf.maximum(0.0, F0 - margin0), 2)
F1 = tf.pow(tf.maximum(0.0, margin1 - F0), 2)
intra_loss = tf.reduce_mean(tf.multiply(F0,1.0))
inter_loss = tf.reduce_mean(tf.multiply(F1, 1.0 - 1.0))
Ld = (intra_loss + inter_loss) / (batch_size * batch_size)
return Lc + Ld

inputs = tf.keras.Input(shape=(24,24, 3))
model = tf.keras.Model(inputs=inputs, outputs=Net(inputs,)[0])
pred = DieNet(inputs)[0]
H =DieNet(inputs)[1]
logits = DieNet(inputs)[2]

loss_n=loss_function(H, logits)
model.compile(loss=loss_n,
optimizer=tf.keras.optimizers.Adam(learning_rate=1e-2),
metrics=[‘accuracy’])

model.fit(train, batch_size=32, epochs=200, validation_data=val)