import tensorflow as tf
from tensorflow.keras import layers, models
# Define custom loss function
# Penalize false negatives more by weighting them higher
def custom_weighted_binary_crossentropy(y_true, y_pred):
epsilon = 1e-7
y_pred = tf.clip_by_value(y_pred, epsilon, 1 - epsilon)
# Calculate standard binary crossentropy
bce = -(y_true * tf.math.log(y_pred) + (1 - y_true) * tf.math.log(1 - y_pred))
# Weight false negatives higher: when y_true=1 and y_pred is low
weight = 1 + 2 * y_true * (1 - y_pred) # weight >1 for false negatives
weighted_bce = weight * bce
return tf.reduce_mean(weighted_bce)
# Sample model architecture (same as before)
model = models.Sequential([
layers.Input(shape=(28, 28, 1)),
layers.Conv2D(32, 3, activation='relu'),
layers.MaxPooling2D(),
layers.Flatten(),
layers.Dense(64, activation='relu'),
layers.Dense(1, activation='sigmoid')
])
model.compile(optimizer='adam', loss=custom_weighted_binary_crossentropy, metrics=['accuracy'])
# Dummy data for demonstration (replace with real data)
import numpy as np
X_train = np.random.rand(1000, 28, 28, 1).astype('float32')
y_train = np.random.randint(0, 2, 1000).astype('float32')
X_val = np.random.rand(200, 28, 28, 1).astype('float32')
y_val = np.random.randint(0, 2, 200).astype('float32')
# Train model
history = model.fit(X_train, y_train, epochs=10, batch_size=32, validation_data=(X_val, y_val))