名称错误:K 未定义(即使 K 已定义并使用)

问题描述 投票:0回答:1

我正在学习 ML/DL,并希望创建一个暹罗神经网络 (SNN) 来识别人脸。

这就是我导入 train.py 文件的方式:

import os
import numpy as np
import cv2
import tensorflow as tf
from keras.models import Model
from keras.layers import Input, Conv2D, MaxPooling2D, Flatten, Dense, Lambda
from keras import backend as K
from keras.optimizers import Adam
from sklearn.model_selection import train_test_split
from utils import create_pairs, load_images_and_labels, save_embeddings

文件 train.py 按预期运行。

但是当我运行我的 recognize.py 文件时。

import cv2
import numpy as np
from keras.models import load_model
from utils import load_embeddings

# Load the trained model and embeddings
siamese_model = load_model('models/siamese_model.h5', compile=False)
registered_embeddings = load_embeddings('models/embeddings.pkl')
base_network = siamese_model.layers[2]  # Extract the base network

# Initialize the face detector
facedetect = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')

# Function to recognize faces in real time
def recognize_face(frame, base_network, registered_embeddings, threshold=0.5):
    faces = facedetect.detectMultiScale(frame, 1.3, 5)
    for x, y, w, h in faces:
        face = frame[y:y+h, x:x+w]
        face = cv2.resize(face, (100, 100))
        face = face.astype('float32') / 255.0
        face = np.expand_dims(face, axis=0)
        
        # Generate embedding for the detected face
        face_embedding = base_network.predict(face)

        # Compare with registered embeddings
        min_dist = float('inf')
        person_name = "Unknown"
        for name, embedding in registered_embeddings.items():
            dist = np.linalg.norm(face_embedding - embedding)
            if dist < min_dist and dist < threshold:
                min_dist = dist
                person_name = name

        # Draw bounding box and name
        cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
        cv2.putText(frame, person_name, (x, y-10), cv2.FONT_HERSHEY_SIMPLEX, 
                    0.9, (255, 255, 255), 2)

    cv2.imshow("Face Recognition", frame)

# Real-time webcam feed
video = cv2.VideoCapture(0)
while True:
    ret, frame = video.read()
    recognize_face(frame, base_network, registered_embeddings)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

video.release()
cv2.destroyAllWindows()

出现此错误: 回溯(最近一次调用最后一次): 文件“/Users/mac/face_recognition_system/人脸识别系统/recognize.py”,第7行,位于 siamese_model = load_model('models/siamese_model.h5',compile=False) 文件“/Users/mac/face_recognition_system/人脸识别系统/face_recognition/lib/python3.9/site-packages/keras/utils/traceback_utils.py”,第70行,在error_handler中 从 None 引发 e.with_traceback(filtered_tb) 文件“/Users/mac/face_recognition_system/Face Recognition System/train.py”,第 31 行,在 euclidean_distance 中 sumSquared = K.sum(K.square(featsA - featsB), axis=1, keepdims=True)

NameError:调用层“lambda”(Lambda 类型)时遇到异常。 名称“K”未定义

调用“lambda”层接收的参数(Lambda 类型): • 输入=['tf.Tensor(shape=(None, 4096), dtype=float32)', 'tf.Tensor(shape=(None, 4096), dtype=float32)'] • 掩码=无 • 培训=无

*注意:即使已经安装了tensorflow,我也无法使用tensorflow.keras.X(X是任何东西),因为它说无法解析。 如果有的话,我正在使用 VS 代码。

python keras import
1个回答
0
投票

我通过在 recognize.py 文件中导入 Keras 后端并在文件开头添加 K.clear_session() 来修复此问题。

© www.soinside.com 2019 - 2024. All rights reserved.