Spaces:
Sleeping
Sleeping
Create model.py
Browse files
model.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# ----------------------------------------------------------
|
| 2 |
+
# Enhanced Embedding Network
|
| 3 |
+
# ----------------------------------------------------------
|
| 4 |
+
import keras
|
| 5 |
+
from keras_facenet import FaceNet
|
| 6 |
+
from app import eucledian_distance
|
| 7 |
+
|
| 8 |
+
def build_embedding_network(input_shape):
|
| 9 |
+
# Load the FaceNet model
|
| 10 |
+
facenet = FaceNet()
|
| 11 |
+
base_model = facenet.model
|
| 12 |
+
|
| 13 |
+
# Freeze all layers except the last 10 for fine-tuning
|
| 14 |
+
for layer in base_model.layers[:-10]:
|
| 15 |
+
layer.trainable = False
|
| 16 |
+
|
| 17 |
+
# Define input and pass it through the base model
|
| 18 |
+
inputs = keras.Input(input_shape)
|
| 19 |
+
x = base_model(inputs) # Pass input through FaceNet
|
| 20 |
+
|
| 21 |
+
# Final Embedding Layer
|
| 22 |
+
x = layers.Dense(256, activation=None)(x) # No activation before L2 norm
|
| 23 |
+
x = layers.Lambda(lambda x: tf.math.l2_normalize(x, axis=1))(x) # L2-normalized embeddings
|
| 24 |
+
|
| 25 |
+
return keras.Model(inputs, x)
|
| 26 |
+
|
| 27 |
+
# ----------------------------------------------------------
|
| 28 |
+
# Siamese Network
|
| 29 |
+
# ----------------------------------------------------------
|
| 30 |
+
def build_siamese():
|
| 31 |
+
|
| 32 |
+
input_shape = (256, 256, 3) # FaceNet expects 160x160 input
|
| 33 |
+
embedding_network = build_embedding_network(input_shape)
|
| 34 |
+
|
| 35 |
+
# Define inputs for the Siamese network
|
| 36 |
+
input_1 = layers.Input(input_shape)
|
| 37 |
+
input_2 = layers.Input(input_shape)
|
| 38 |
+
|
| 39 |
+
# Pass inputs through the embedding network
|
| 40 |
+
tower_1 = embedding_network(input_1)
|
| 41 |
+
tower_2 = embedding_network(input_2)
|
| 42 |
+
|
| 43 |
+
# Compute Euclidean distance between embeddings
|
| 44 |
+
distance = layers.Lambda(euclidean_distance, name='distance_layer')([tower_1, tower_2])
|
| 45 |
+
|
| 46 |
+
# Custom Contrastive Output Layer
|
| 47 |
+
output = layers.Dense(1, activation='sigmoid',
|
| 48 |
+
kernel_regularizer=keras.regularizers.l2(1e-4))(distance)
|
| 49 |
+
|
| 50 |
+
# Build the Siamese model
|
| 51 |
+
siamese = keras.Model(inputs=[input_1, input_2], outputs=output)
|
| 52 |
+
siamese.summary()
|