首页 > 编程问答 >面部识别 - 机器学习

面部识别 - 机器学习

时间:2024-08-01 07:56:22浏览次数:8  
标签:python machine-learning artificial-intelligence facial-identification

我正在尝试在 Google Colab 上使用 Tensorflow 进行面部识别,但遇到错误。以前工作得很好,但现在却抛出了这个错误。完整的 .ipynb 文件已链接(请注意,您需要一个包含 .jpg 文件的负数、正数和锚文件夹才能运行程序。) 使暹罗模型出错 文件链接: https://www .mediafire.com/file/a5azngcpmdrrxyd/facial_recognition.ipynb/file

我尝试从 4.3 函数中删除嵌入函数,但在训练时它又抛出了另一个错误。 训练错误


我查看了提供的代码和错误消息。看来问题出在 试图将不兼容的张量传递给损失函数 。更具体地说,的 TripletLoss 函数返回一个形状为 (batch_size,) 的张量,而 model.fit() 函数需要一个标量损失值。

以下是导致此错误的分步说明:

  1. TripletLoss 函数计算批次中每个三元组的标量损失。 这是正确的。
  2. 然后,它使用 tf.reduce_mean() 对所有这些标量损失求平均值。 这也是正确的,因为它可以为提供一个批次的平均三元组损失。
  3. 问题在于 model.fit() 函数期望将一个 标量 值作为损失。 它不知道如何处理形状为 (batch_size,) 的张量。

为了解决此错误,需要 TripletLoss 函数内聚合三元组损失 。可以通过以下两种方式之一来执行此操作:

选项 1:将损失减少为单个标量

最简单的方法是在 tf.reduce_mean() 之后返回三元组损失的单个标量。这将为提供整个批次的单个平均损失值。

def TripletLoss(margin=0.5):
    def _TripletLoss(y_true, y_pred):
        anchor, positive, negative = y_pred[:,:128], y_pred[:,128:256], y_pred[:,256:]

        positive_dist = tf.reduce_sum(tf.square(anchor - positive), axis=1)
        negative_dist = tf.reduce_sum(tf.square(anchor - negative), axis=1)

        triplet_loss = tf.maximum(positive_dist - negative_dist + margin, 0.0)
        loss = tf.reduce_mean(triplet_loss)  # Calculate the mean triplet loss
        return loss  # Return the scalar loss value
    return _TripletLoss 

选项 2:使用 tf.keras.losses.Loss 基类

还可以通过子类化 tf.keras.losses.Loss 并实现 call() 方法来创建一个自定义损失函数。这使可以更好地控制损失计算,并且在处理加权损失或需要在损失函数内部执行其他操作时非常有用。

class TripletLoss(tf.keras.losses.Loss):
    def __init__(self, margin=0.5):
        super(TripletLoss, self).__init__()
        self.margin = margin

    def call(self, y_true, y_pred):
        anchor, positive, negative = y_pred[:,:128], y_pred[:,128:256], y_pred[:,256:]

        positive_dist = tf.reduce_sum(tf.square(anchor - positive), axis=1)
        negative_dist = tf.reduce_sum(tf.square(anchor - negative), axis=1)

        triplet_loss = tf.maximum(positive_dist - negative_dist + self.margin, 0.0)
        return triplet_loss # Return the triplet losses for each sample in the batch

在对 TripletLoss 函数进行此更改后,请确保像这样创建损失函数的实例:

triplet_loss = TripletLoss() # For option 1
# OR
triplet_loss = TripletLoss(margin=0.5) # For option 2

并使用它来编译的模型:

model.compile(loss=triplet_loss, optimizer='adam')

通过在 TripletLoss 函数中聚合损失或使用 tf.keras.losses.Loss 基类并返回正确的损失形状,应该可以解决 model.fit() 中的错误。

标签:python,machine-learning,artificial-intelligence,facial-identification
From: 78818666

相关文章

  • ffmpeg python 导致死锁
    我在使用ffmpegpython处理相机帧时遇到问题。我使用process.communicate()的第一种方法效果很好,但存在延迟问题。process=(ffmpeg.input('pipe:',format='rawvideo',pix_fmt='rgb24',s='{}x{}'.format(width,height))......
  • 将 HTTP 分块编码数据流代码片段从 Node.js 转换为 Python
    我有一个Node.js客户端代码,它将请求发送到HTTP服务器,然后连续接收分块编码数据。这是带有一些流量数据输出的Node.js代码。consthttp=require('http');constoptions={hostname:'...',path:'...',port:...,...};constreq=http.request(......
  • vsc python 调试器和 pylance 无法识别已安装的包
    我最近使用snowflake-connector-python在我的虚拟环境中安装了pipinstallsnowflake-connector-python[pandas]==2.7.6,当我在激活虚拟环境的情况下从命令行运行我的脚本时,它工作正常。我设置了与VSC解释器相同的虚拟环境,但尝试运行python调试器会引发异常......
  • 如何从python读取matlab持续时间对象
    我创建一个matlab持续时间对象并将其保存到.mat文件:timeend=seconds(123);save('time.mat',timeend,'-v7.3');然后我从python读取它:withh5py.File('time.mat','r')asf:var=f['timeend'][:]print(list(var))......
  • 通过 python 连接到 Snowflake 时出错“UnpicklingError: invalid load key, '\x00'
    我在使用snowflake.connector.connect通过python连接到snowflake时遇到以下错误importsnowflake.connector#pipinstallsnowflake-connector-python#iamgettingtheenvfrom.envfileistoredlocallycnx=snowflake.connector.connect(user=os.getenv('USER'),pass......
  • Python Selenium 单击 webdriverwait 与 find_element
    我无法理解这两个代码块之间的区别。发送点击在webdriverwait和find_elements中都有效。代码1fromseleniumimportwebdriverfromselenium.webdriver.common.byimportByfromselenium.webdriver.support.uiimportWebDriverWaitfromselenium.webdriver.suppo......
  • Python 问题 如何创建在 PDF 中注册为剪切线的专色?
    我正在开发一个项目,需要我在图像周围创建一条剪切线,但在任何RIP程序(例如Versaworks或Flexi)上将其注册为实际剪切线时遇到困难。我尝试了很多不同的方法python库可以帮助解决这个问题,但我无法让它工作。我希望它像我们在Illustrator中所做的那样,创建一条名为CutConto......
  • 使用Python时如何避免`setattr`(和`getattr`)?以及是否有必要避免
    如果我想向协议缓冲区中的字段添加一个在编译时未知的值,我目前正在做setattr我通常不喜欢使用setattr,因为它看起来不太安全。但是当我知道该对象是protobuf时,我认为这很好,因为我设置它的值必须是protobuf允许的类型。所以也许它并不是真的不安全?让我举......
  • Java sshtools 生成的 EDDSA 签名与 Python 的 pycryptome 生成的签名不匹配
    我有一个python库,它使用pycryptodomelibrary使用openssh格式的ED25519私钥使用Ed25519算法对数据进行签名。然后需要使用sshtools库和相应的公钥在Java应用程序中验证签名。但是签名验证失败。约束:从文件中读取私钥/公钥很重要。我无法......
  • Elastic python请求超时错误:池达到最大大小,不允许更多连接
    我正在使用Elasticsearchpython模块。我正在尝试像这样建立到服务器的连接es=Elasticsearch([config.endpoint],api_key=config.key,request_timeout=config.request_timeout)服务器连接,然后我尝试执行丰富策略。es.enr......