问题描述:我正在开发一个用 Python 构建并使用 MySQL 数据库的监考考试系统。该系统包括一项在考试期间监控学生的功能(包括客观和
问题描述:
我正在开发一个用 Python 构建并使用 MySQL 数据库的监考考试系统。该系统包括一项功能,用于使用 TensorFlow 进行面部特征检测,在考试期间(客观和主观)监控学生。最近,在升级库并尝试匹配新趋势和标准后,我遇到了一个问题,即监控屏幕无法正确显示。我已经成功运行了该项目,并且一些功能正常运行。
错误信息:
`*WARNING:tensorflow:From E:\ExamAi\myenv\Lib\site-packages\tf_keras\src\losses.py:2976: The name tf.losses.sparse_softmax_cross_entropy is deprecated. Please use tf.compat.v1.losses.sparse_softmax_cross_entropy instead.
2024-07-16 19:38:07.825537: I tensorflow/core/platform/cpu_feature_guard.cc:210] This TensorFlow binary is optimized to use available CPU instructions in performance-critical operations.
To enable the following instructions: AVX2 FMA, in other operations, rebuild TensorFlow with the appropriate compiler flags.
Error loading the landmark model from models/pose_model.keras: Error when deserializing class 'InputLayer' using config={'batch_shape': [None, 4], 'dtype': 'float32', 'sparse': False, 'name': 'input_layer'}.
Exception encountered: Unrecognized keyword arguments: ['batch_shape']`
face_landmark.py:
import cv2
import numpy as np
import tensorflow as tf
from tensorflow import keras
def get_landmark_model(saved_model="models/pose_model.keras"):
try:
model = tf.keras.models.load_model(saved_model)
return model
except Exception as e:
print(f"Error loading the landmark model from {saved_model}: {e}")
return None
def get_square_box(box):
left_x = box[0]
top_y = box[1]
right_x = box[2]
bottom_y = box[3]
box_width = right_x - left_x
box_height = bottom_y - top_y
diff = box_height - box_width
delta = int(abs(diff) / 2)
if diff == 0: # Already a square.
return box
elif diff > 0: # Height > width, a slim box.
left_x -= delta
right_x += delta
if diff % 2 == 1:
right_x += 1
else: # Width > height, a short box.
top_y -= delta
bottom_y += delta
if diff % 2 == 1:
bottom_y += 1
assert ((right_x - left_x) == (bottom_y - top_y)), 'Box is not square.'
return [left_x, top_y, right_x, bottom_y]
def move_box(box, offset):
left_x = box[0] + offset[0]
top_y = box[1] + offset[1]
right_x = box[2] + offset[0]
bottom_y = box[3] + offset[1]
return [left_x, top_y, right_x, bottom_y]
def detect_marks(img, model, face):
offset_y = int(abs((face[3] - face[1]) * 0.1))
box_moved = move_box(face, [0, offset_y])
facebox = get_square_box(box_moved)
h, w = img.shape[:2]
if facebox[0] < 0:
facebox[0] = 0
if facebox[1] < 0:
facebox[1] = 0
if facebox[2] > w:
facebox[2] = w
if facebox[3] > h:
facebox[3] = h
face_img = img[facebox[1]: facebox[3], facebox[0]: facebox[2]]
face_img = cv2.resize(face_img, (320, 320))
face_img = cv2.cvtColor(face_img, cv2.COLOR_BGR2RGB)
predictions = model.signatures["predict"](tf.constant([face_img], dtype=tf.uint8))
marks = np.array(predictions['output']).flatten()[:136]
marks = np.reshape(marks, (-1, 2))
marks *= (facebox[2] - facebox[0])
marks[:, 0] += facebox[0]
marks[:, 1] += facebox[1]
marks = marks.astype(np.uint)
return marks
保存的模型.py:
import os
import tensorflow as tf
import numpy as np
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
def build_model(input_shape):
model = tf.keras.Sequential([
tf.keras.layers.Input(shape=input_shape, name='input_layer'),
tf.keras.layers.Dense(10, activation='relu'),
tf.keras.layers.Dense(3, activation='softmax') # 3 classes for Iris dataset
])
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
return model
def main():
# Load Iris dataset
iris = load_iris()
X = iris.data
y = iris.target
# Split data into training and validation sets
x_train, x_val, y_train, y_val = train_test_split(X, y, test_size=0.2, random_state=42)
# Standardize the data (mean=0, variance=1)
scaler = StandardScaler()
x_train = scaler.fit_transform(x_train)
x_val = scaler.transform(x_val)
# Build the model
input_shape = (x_train.shape[1],) # Number of features
model = build_model(input_shape)
# Train the model
model.fit(x_train, y_train, epochs=10, batch_size=32, validation_data=(x_val, y_val))
# Save the model in the Keras format
model_file = 'models/pose_model.keras'
if not os.path.exists('models'):
os.makedirs('models')
if os.path.exists(model_file):
os.remove(model_file)
tf.keras.models.save_model(model, model_file, save_format='keras')
print("Model saved successfully.")
# Load the model back to check if saved correctly
loaded_model = tf.keras.models.load_model(model_file, custom_objects={'InputLayer': tf.keras.layers.InputLayer})
print("Model loaded successfully.")
# Optionally, test the loaded model
predictions = loaded_model.predict(x_val[:5])
print("Predictions:", predictions)
if __name__ == "__main__":
main()
补充笔记:
我尝试通过 save_model.py 创建一个新的 pose_model.keras,但问题仍然存在。寻求帮助以尽快解决此问题,因为它对于演示至关重要。要求:
我将非常感激任何有关解决此问题的帮助或指导,尤其是与 TensorFlow 模型加载和 InputLayer 配置相关的帮助或指导。我也可以参加任何在线会议。