python-3.x - 如何紧固Knn算法进行实时人脸识别
问题描述
我正在做人脸检测和识别方面的工作,我想实时检测人脸,
但是到了训练的地步,需要很长时间来训练
数据是否可以减少训练的时间数据可以帮助任何人
我解决了这个问题
'''
def train(train_dir, model_save_path=None, n_neighbors=None, knn_algo='ball_tree', verbose=False):
X = []
y = []
# Loop through each person in the training set
for class_dir in tqdm(os.listdir(train_dir)):
if not os.path.isdir(os.path.join(train_dir, class_dir)):
continue
# Loop through each training image for the current person
for img_path in image_files_in_folder(os.path.join(train_dir, class_dir)):
image = face_recognition.load_image_file(img_path)
face_bounding_boxes = face_recognition.face_locations(image)
if len(face_bounding_boxes) != 1:
# If there are no people (or too many people) in a training image, skip the image.
if verbose:
print("Image {} not suitable for training: {}".format(img_path, "Didn't find a face" if len(face_bounding_boxes) < 1 else "Found more than one face"))
else:
# Add face encoding for current image to the training set
X.append(face_recognition.face_encodings(image, known_face_locations=face_bounding_boxes)[0])
y.append(class_dir.split('_')[0])
# Determine how many neighbors to use for weighting in the KNN classifier
if n_neighbors is None:
n_neighbors = int(round(math.sqrt(len(X))))
if verbose:
print("Chose n_neighbors automatically:", n_neighbors)
# Create and train the KNN classifier
knn_clf = neighbors.KNeighborsClassifier(n_neighbors=n_neighbors, algorithm=knn_algo, weights='distance')
print(knn_clf)
knn_clf.fit(X, y)
# Save the trained KNN classifier
if model_save_path is not None:
with open(model_save_path, 'wb') as f:
pickle.dump(knn_clf, f)
return knn_clf
'''
这是最后的电话
'''
def trainer():
# STEP 1: Train the KNN classifier and save it to disk
# Once the model is trained and saved, you can skip this step next time.
print("Training KNN classifier...")
classifier = train("app/facerec/dataset", model_save_path="app/facerec/models/trained_model.clf", n_neighbors=3)
print("Training complete!")
'''
还想知道是否有任何可能性,而不是重写“trained_model.clf”文件,我们可以更新文件。
解决方案
训练 kNN 模型不应强加高运行时开销。毕竟,直接(“精确搜索”)模型是懒惰的。它存储向量并在查询(或分类)时执行蛮力搜索。
我推测嵌入计算会支配你的训练时间。
正如@johncasey 所提到的,您可能想要使用近似kNN 模型(或相似性搜索引擎)。有许多开源相似性搜索库。然而,如果您需要一个可用于生产的、强大的、实时的、高效的解决方案,那么您应该查看pinecone.io。(免责声明,我为 Pinecone 工作。)
推荐阅读
- excel - 在另一张纸中搜索文本列表并将所有匹配复制到不同的纸上
- php - Laravel PHP - 将字符串从数据库转换为数组
- python - 两个DataFrame列与group by之间的区别
- bash - 如何在引号中抓取字段
- android - 无效的
对于给定的资源价值 - javascript - 如何在不复制的情况下在左列和右列中显示视频?
- c - 即使我只分配了 1MB 的内存,为什么 malloc 会返回一个 NULL 指针?
- python - 连接目录中的文件,更改格式
- asp.net-mvc - MVC 验证似乎不适用于文本字段,但适用于数字字段
- elasticsearch - 在弹性搜索布尔查询中,必须和过滤器如何一起解释?