Introduction
Sometimes, the built-in loss functions do not fit your problem well. Custom loss functions let you tell the model exactly how to measure errors in a way that matches your goal.
def custom_loss(y_true, y_pred): loss = some_operations_on(y_true, y_pred) return loss
def mean_absolute_error(y_true, y_pred): return tf.reduce_mean(tf.abs(y_true - y_pred))
def squared_error_with_penalty(y_true, y_pred): base_loss = tf.reduce_mean(tf.square(y_true - y_pred)) penalty = 0.1 * tf.reduce_mean(tf.square(y_pred)) return base_loss + penalty
import tensorflow as tf # Define a simple custom loss function @tf.function def custom_mse(y_true, y_pred): return tf.reduce_mean(tf.square(y_true - y_pred)) # Create some sample data x = tf.constant([[1.0], [2.0], [3.0], [4.0]]) y = tf.constant([[2.0], [4.0], [6.0], [8.0]]) # Build a simple linear model model = tf.keras.Sequential([ tf.keras.layers.Dense(1, input_shape=(1,)) ]) # Compile the model with the custom loss model.compile(optimizer='sgd', loss=custom_mse, metrics=['mse']) # Train the model history = model.fit(x, y, epochs=5, verbose=0) # Make predictions predictions = model.predict(x) # Print training loss and predictions print(f"Final training loss: {history.history['loss'][-1]:.4f}") print("Predictions:") print(predictions)
custom loss function in TensorFlow?y_true = [2.0, 3.0] and y_pred = [1.0, 5.0]?
def custom_loss(y_true, y_pred):
return tf.reduce_sum(tf.abs(y_true - y_pred))def custom_loss(y_true, y_pred):
return tf.reduce_mean(y_true - y_pred)Pass the test and this pattern moves unknown