Prabin1's picture
Rename model_utilis.py to model_utils.py
148368a verified
Raw
History Blame Contribute Delete
1.89 kB
import numpy as np
import tensorflow as tf
def load_model(model_path):
print(f"Loading model from {model_path}...")
model = tf.keras.models.load_model(model_path)
print("Model loaded successfully.")
return model
def prepare_input_for_model(features, model):
"""Resize and batch the features to match model input."""
features = np.asarray(features, dtype=np.float32)
target_shape = model.input_shape[1:]
if len(target_shape) == 2:
target_T, target_D = target_shape
if target_D is not None and target_D != features.shape[1]:
features = features.T
if target_T is not None:
cur_T = features.shape[0]
if cur_T < target_T:
pad = np.zeros((target_T - cur_T, features.shape[1]))
features = np.vstack([features, pad])
else:
features = features[:target_T, :]
elif len(target_shape) == 1:
flat = features.flatten()
target_len = target_shape[0]
if target_len is not None:
if flat.shape[0] < target_len:
flat = np.pad(flat, (0, target_len - flat.shape[0]))
else:
flat = flat[:target_len]
features = flat
else:
raise ValueError(f"Unsupported input shape {target_shape}")
return np.expand_dims(features, axis=0)
def interpret_prediction(raw_pred):
"""Turn model output into readable Real/Fake probabilities."""
raw = np.asarray(raw_pred).squeeze()
if raw.size == 1:
val = float(raw)
prob_fake = val if 0.0 <= val <= 1.0 else 1 / (1 + np.exp(-val))
else:
probs = tf.nn.softmax(raw).numpy()
prob_fake = float(probs[1]) if probs.size >= 2 else float(probs.max())
prob_fake = float(np.clip(prob_fake, 0, 1))
prob_real = 1 - prob_fake
return {"Fake": prob_fake, "Real": prob_real}