smart-election-verification / src /siamese_model.py
selvaneyas's picture
Upload 7 files
e619b9a verified
#src/siamese_model.py
import tensorflow as tf
from tensorflow.keras import layers, Model
from tensorflow.keras.utils import plot_model
IMG_SIZE = (128, 128, 1)
def build_embedding():
inp = layers.Input(shape=IMG_SIZE)
x = layers.Conv2D(32, 3, activation="relu")(inp)
x = layers.MaxPooling2D()(x)
x = layers.Conv2D(64, 3, activation="relu")(x)
x = layers.MaxPooling2D()(x)
x = layers.Flatten()(x)
x = layers.Dense(128, activation="relu")(x)
return Model(inp, x, name="embedding")
def build_siamese_model(visualize=False):
embedding = build_embedding()
img1 = layers.Input(shape=IMG_SIZE, name="img1")
img2 = layers.Input(shape=IMG_SIZE, name="img2")
f1 = embedding(img1)
f2 = embedding(img2)
# Simplified absolute difference layer
distance = layers.Lambda(lambda tensors: tf.abs(tensors[0] - tensors[1]))([f1, f2])
output = layers.Dense(1, activation="sigmoid")(distance)
model = Model(inputs=[img1, img2], outputs=output, name="Siamese_Network")
if visualize:
plot_model(model, to_file='siamese_architecture.png', show_shapes=True, show_layer_names=True)
print("✅ Model architecture saved as 'siamese_architecture.png'")
return model
# import tensorflow as tf
# from tensorflow.keras import layers, Model
# IMG_SIZE = (128, 128, 1)
# def build_embedding():
# inp = layers.Input(shape=IMG_SIZE)
# x = layers.Conv2D(32, 3, activation="relu")(inp)
# x = layers.MaxPooling2D()(x)
# x = layers.Conv2D(64, 3, activation="relu")(x)
# x = layers.MaxPooling2D()(x)
# x = layers.Flatten()(x)
# x = layers.Dense(128, activation="relu")(x)
# return Model(inp, x, name="embedding")
# def build_siamese_model():
# embedding = build_embedding()
# img1 = layers.Input(shape=IMG_SIZE, name="img1")
# img2 = layers.Input(shape=IMG_SIZE, name="img2")
# f1 = embedding(img1)
# f2 = embedding(img2)
# # ✅ SAFE, SERIALIZABLE (NO Lambda)
# distance = layers.Subtract()([f1, f2])
# distance = layers.Lambda(lambda x: tf.abs(x))(distance)
# output = layers.Dense(1, activation="sigmoid")(distance)
# return Model(inputs=[img1, img2], outputs=output)