进程完成,退出代码 137(被信号 9 中断:SIGKILL):检索图像数据

2024-03-08

我从人脸图像中提取特征,然后使用不同的相似性度量将特征与其他图像进行比较。以前,图像名称列表很小,但工作正常。代表每个图像的整个列表我将这些列表放入 json 文件中并在 python 文件中使用。当我增加图像时,PyCharm 会终止我的进程。

import pandas as pd
import numpy as np
import itertools
from sklearn import metrics
from sklearn.metrics import confusion_matrix, accuracy_score, roc_curve, auc
import matplotlib.pyplot as plt
import json
from tqdm import tqdm
from sklearn.utils.multiclass import type_of_target

import os

os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
import tensorflow as tf

tf.compat.v1.disable_eager_execution()

with open('/home/khawar/deepface/tests/ageDB.json') as f:
    data = json.load(f)

idendities = data

# --------------------------
# Data set

# Ref: https://github.com/serengil/deepface/tree/master/tests/dataset

# --------------------------
# Positives

positives = []

for key, values in idendities.items():

    # print(key)
    for i in range(0, len(values) - 1):
        for j in range(i + 1, len(values)):
            # print(values[i], " and ", values[j])
            positive = []
            positive.append(values[i])
            positive.append(values[j])
            positives.append(positive)

positives = pd.DataFrame(positives, columns=["file_x", "file_y"])
positives["decision"] = "Yes"
print(positives.shape)
# --------------------------
# Negatives

samples_list = list(idendities.values())

negatives = []

for i in range(0, len(idendities) - 1):
    for j in range(i + 1, len(idendities)):
        # print(samples_list[i], " vs ",samples_list[j])
        cross_product = itertools.product(samples_list[i], samples_list[j])
        cross_product = list(cross_product)
        # print(cross_product)

        for cross_sample in cross_product:
            # print(cross_sample[0], " vs ", cross_sample[1])
            negative = []
            negative.append(cross_sample[0])
            negative.append(cross_sample[1])
            negatives.append(negative)

negatives = pd.DataFrame(negatives, columns=["file_x", "file_y"])
negatives["decision"] = "No"

negatives = negatives.sample(positives.shape[0])

print(negatives.shape)
# --------------------------
# Merge positive and negative ones

df = pd.concat([positives, negatives]).reset_index(drop=True)

print(df.decision.value_counts())

df.file_x = "deepface/tests/dataset/" + df.file_x
df.file_y = "deepface/tests/dataset/" + df.file_y
# --------------------------
# DeepFace

from deepface import DeepFace
from deepface.basemodels import VGGFace, OpenFace, Facenet, FbDeepFace

pretrained_models = {}

pretrained_models["VGG-Face"] = VGGFace.loadModel()
print("VGG-Face loaded")
pretrained_models["Facenet"] = Facenet.loadModel()
print("Facenet loaded")
pretrained_models["OpenFace"] = OpenFace.loadModel()
print("OpenFace loaded")
pretrained_models["DeepFace"] = FbDeepFace.loadModel()
print("FbDeepFace loaded")

instances = df[["file_x", "file_y"]].values.tolist()

models = ['VGG-Face']
metrics = ['cosine']

if True:
    for model in models:
        for metric in metrics:

            resp_obj = DeepFace.verify(instances
                                       , model_name=model
                                       , model=pretrained_models[model]
                                       , distance_metric=metric)

            distances = []

            for i in range(0, len(instances)):
                distance = round(resp_obj["pair_%s" % (i + 1)]["distance"], 4)
                distances.append(distance)

            df['%s_%s' % (model, metric)] = distances

    df.to_csv("face-recognition-pivot.csv", index=False)
else:
    df = pd.read_csv("face-recognition-pivot.csv")

df_raw = df.copy()

# --------------------------
# Distribution

fig = plt.figure(figsize=(15, 15))

figure_idx = 1
for model in models:
    for metric in metrics:
        feature = '%s_%s' % (model, metric)

        ax1 = fig.add_subplot(4, 2, figure_idx)

        df[df.decision == "Yes"][feature].plot(kind='kde', title=feature, label='Yes', legend=True)
        df[df.decision == "No"][feature].plot(kind='kde', title=feature, label='No', legend=True)

        figure_idx = figure_idx + 1

# plt.show()
# --------------------------
# Pre-processing for modelling

columns = []
for model in models:
    for metric in metrics:
        feature = '%s_%s' % (model, metric)
        columns.append(feature)

columns.append("decision")

df = df[columns]

df.loc[df[df.decision == 'Yes'].index, 'decision'] = 1
df.loc[df[df.decision == 'No'].index, 'decision'] = 0

print(df.head())
# --------------------------
# Train test split

from sklearn.model_selection import train_test_split

df_train, df_test = train_test_split(df, test_size=0.30, random_state=17)

target_name = "decision"

y_train = df_train[target_name].values
x_train = df_train.drop(columns=[target_name]).values

y_test = df_test[target_name].values
x_test = df_test.drop(columns=[target_name]).values

# --------------------------
# LightGBM

import lightgbm as lgb

features = df.drop(columns=[target_name]).columns.tolist()
lgb_train = lgb.Dataset(x_train, y_train, feature_name=features)
lgb_test = lgb.Dataset(x_test, y_test, feature_name=features)

params = {
    'task': 'train'
    , 'boosting_type': 'gbdt'
    , 'objective': 'multiclass'
    , 'num_class': 2
    , 'metric': 'multi_logloss'
}

gbm = lgb.train(params, lgb_train, num_boost_round=250, early_stopping_rounds=15, valid_sets=lgb_test)

gbm.save_model("face-recognition-ensemble-model.txt")

# --------------------------
# Evaluation

predictions = gbm.predict(x_test)

predictions_classes = []
for i in predictions:
    prediction_class = np.argmax(i)
    predictions_classes.append(prediction_class)

cm = confusion_matrix(list(y_test), predictions_classes)

tn, fp, fn, tp = cm.ravel()

recall = tp / (tp + fn)
precision = tp / (tp + fp)
accuracy = (tp + tn) / (tn + fp + fn + tp)
f1 = 2 * (precision * recall) / (precision + recall)

print("Precision: ", 100 * precision, "%")
print("Recall: ", 100 * recall, "%")
print("F1 score ", 100 * f1, "%")
print("Accuracy: ", 100 * accuracy, "%")


# --------------------------
# Interpretability

ax = lgb.plot_importance(gbm, max_num_features=20)
# plt.show()

import os

os.environ["PATH"] += os.pathsep + 'C:/Program Files (x86)/Graphviz2.38/bin'

plt.rcParams["figure.figsize"] = [20, 20]

for i in range(0, gbm.num_trees()):
    ax = lgb.plot_tree(gbm, tree_index=i)
    # plt.show()

    if i == 2:
        break
# --------------------------
# ROC Curve

from sklearn.metrics import confusion_matrix, accuracy_score, roc_auc_score, roc_curve

y_pred_proba = predictions[::, 1]
y_test = y_test.astype(int)


fpr, tpr, _ = roc_curve(y_test, y_pred_proba)
auc = roc_auc_score(y_test, y_pred_proba)

plt.figure(figsize=(4, 4))
lw = 2

plt.plot([0, 1], [0, 1], color='navy', lw=lw, linestyle='--')
fig.savefig('/home/khawar/deepface/tests/VGG-FACE_Cosine_ROC.png', dpi=fig.dpi)

plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('VGG Face')
plt.plot(fpr, tpr, label="ROC=" + str(auc))
fig.savefig('/home/khawar/deepface/tests/VGG-FACE_Cosine_ROC_T_F.png', dpi=fig.dpi)

#plt.legend(loc=4)
#fig.savefig('/home/khawar/deepface/tests/VGG-FACE_Cosine.png', dpi=fig.dpi)
plt.show()
# --------------------------

追溯

/home/khawar/anaconda3/envs/deepface/bin/python /home/khawar/deepface/tests/Ensemble-Face-Recognition.py
(236167, 3)

Process finished with exit code 137 (interrupted by signal 9: SIGKILL)

None

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

进程完成,退出代码 137(被信号 9 中断:SIGKILL):检索图像数据 的相关文章

  • 在 HSV 颜色空间内定义组织学图像掩模的颜色范围(Python、OpenCV、图像分析):

    为了根据颜色将组织学切片分成多个层 我修改了 OpenCV 社区提供的一些广泛分布的代码 1 我们的染色程序用不同的颜色标记组织横截面的不同细胞类型 B 细胞为红色 巨噬细胞为棕色 背景细胞核为蓝色 I m interested in se
  • OpenPyXL - 如何查询单元格边框?

    python 和 openpyxl 都是新的 编写一个 py 脚本来遍历大量 Excel 工作簿 工作表 并且需要找到由边框格式标识的某些单元格 我在网上看到几个关于如何设置单元格边框的示例 但我需要阅读它们 具体来说 当表内的数据不一致但
  • 有没有办法拥有租户特定的 JWT 令牌

    我目前正在开发一个 SPA 应用程序 角度 后端使用 Python Flask API 该应用程序将支持多个租户 我对安全概念有点挣扎 我目前正在使用 jwt extend 颁发的 JWT 令牌对所有租户都有效 我当然可以从令牌中获取用户
  • Python 中的自然日/相对日

    我想要一种在 Python 中显示日期项目的自然时间的方法 类似于 Twitter 将显示 刚才 几分钟前 两小时前 三天前 等消息 Django 1 0 在 django contrib 中有一个 人性化 方法 我没有使用 Django
  • 代码运行时出现内存问题(Python、Networkx)

    我编写了一个代码来生成具有 379613734 条边的图 但由于内存问题 代码无法完成 当经过 6200 万行时 大约会占用服务器内存的 97 所以我杀了它 您有解决这个问题的想法吗 我的代码是这样的 import os sys impor
  • 为什么 Python 中的无分支函数和内置函数速度较慢?

    我发现了 2 个无分支函数 它们可以在 python 中查找两个数字的最大值 并将它们与 if 语句和内置 max 函数进行比较 我认为无分支或内置函数将是最快的 但最快的是 if 语句函数 有人知道这是为什么吗 以下是功能 If 语句 2
  • 我应该将Python的pyc文件添加到.dockerignore吗?

    我见过几个例子 dockerignorePython 项目的文件 其中 pyc文件和 或 pycache 文件夹被忽略 pycache pyc 由于无论如何这些文件 文件夹都会在容器中重新创建 我想知道这样做是否是一个好习惯 是的 这是一个
  • 字典键中的通配符

    假设我有一本字典 rank dict V 1 A 2 V 3 A 4 正如您所看到的 我在一个 V 的末尾添加了一个 虽然 3 可能只是 V 的值 但我想要 V1 V2 V2234432 等的另一个密钥 我想检查它 checker V30
  • 计算两个节点之间的最长路径 NetworkX

    我正在尝试使用 Networkx 制作甘特图 网络中的所有节点都是完成项目所需执行的 任务 使用 Networkx 可以轻松计算项目的总时间 但是制作甘特图我需要每个节点的最新启动 NetworkX 包含一个函数 dag longest p
  • 如何在 matplotlib 图中禁用 xkcd?

    您可以通过以下方式打开 xkcd 风格 import matplotlib pyplot as plt plt xkcd 但如何禁用它呢 I try self fig clf 但这行不通 简而言之 要么使用 Valentin 提到的上下文管
  • 如何在 Python 中从 C++/C# 紧密实现 ?: ?

    在 C 中 我可以轻松编写以下内容 string stringValue string IsNullOrEmpty otherString defaultString otherString 有没有一种快速的方法可以在 Python 中做同
  • 如何在Python中使用内联正则表达式修饰符[重复]

    这个问题在这里已经有答案了 我有一个正则表达式 n DOCUMENTATION n n n 2 s 女巫我正在尝试处理这样的一些文件 usr bin python coding utf 8
  • Keras CNN 回归模型损失低,准确度为 0

    我在 keras 中遇到这个 NN 回归模型的问题 我正在研究一个汽车数据集 以根据 13 个维度预测价格 简而言之 我已将其读取为 pandas 数据帧 将数值转换为浮点数 缩放值 然后对分类值使用 one hot 编码 这创建了很多新列
  • 有没有比 ` except: pass` 更简洁的替代方案?

    我有一个函数 可以按偏好顺序返回多个组的随机成员 事情是这样的 def get random foo or bar I d rather have a foo than a bar if there are foos return get
  • 使用 pandas/beautiful soup 抓取表数据(而不是慢的 Selenium?),BS 实现不起作用

    我正在尝试抓取该网站上的网络数据 而我能够访问数据的唯一方法是迭代表的行 将它们添加到列表中 然后将它们添加到 pandas 数据框 写入csv 然后单击下一页并重复该过程 每次搜索大约 50 页 我的程序执行 100 多个搜索 它非常慢
  • 在 Django 中使用 path() 找不到 404

    我刚刚查看 django 并尝试通过视图列出书籍id作为 URL 的参数books urls py 但出现 404 页面未找到错误 当我在浏览器中输入此网址时 我没有发现网址有什么问题 http 192 168 0 106 8000 boo
  • 在 Django 中删除特定用户的所有会话的最优化方法?

    我正在运行 Django 1 3 使用会话中间件和身份验证中间件 settings py SESSION ENGINE django contrib sessions backends db Persist sessions to DB S
  • 为什么使用 LAMP 托管时避免使用 CGI for Python?

    我已经使用 PHP 多年了 最近我在论坛上看到很多帖子说PHP 已经过时了 现代编程语言更简单 更安全等等 所以 我决定开始学习Python 由于我习惯使用 PHP 因此我刚刚开始通过上传 htaccess 文件来构建页面 addtype
  • 如何在 Windows 10 上将 ipynb 文件与 Jupyter Lab(来自 Anaconda)关联

    我使用 Windows 10 Jupiter Lab 是从 Anaconda 安装的 我想交往ipynb使用 Jupyter Lab 保存文件 这样 当我双击ipynb文件应使用 Jupyter Lab 打开 我该怎么做 Install n
  • python nltk从句子中提取关键字

    我们要做的第一件事 就是杀掉所有律师 威廉 莎士比亚 鉴于上面的引用 我想退出 kill and lawyers 作为两个突出的关键词来描述句子的整体含义 我提取了以下名词 动词 POS 标签 First NNP thing NN do V

随机推荐