更新 function.py
Gitea Actions Experiment Test / Experiment-Actions (push) Successful in 20s

This commit is contained in:
2024-10-22 20:01:32 +08:00
parent f2f3e0ef9b
commit 16f4b68716
+19 -5
View File
@@ -45,18 +45,32 @@ import numpy as np
import os import os
from collections import Counter from collections import Counter
def classify(input_vector, dataSet, labels, k=3): # 设置默认值 k=1 def classify_mahalanobis(input_vector, dataSet, labels, k=1):
"""使用 KNN 算法对输入样本进行分类。""" """使用 KNN 算法并基于马氏距离对输入样本进行分类。"""
# 计算输入向量与训练集之间的欧氏距离 # 计算数据集的协方差矩阵及其逆矩阵
distances = np.linalg.norm(dataSet - input_vector, axis=1) cov_matrix = np.cov(dataSet, rowvar=False)
# 对协方差矩阵添加正则化
cov_matrix += np.eye(cov_matrix.shape[0]) * 1e-5
# 计算协方差矩阵的逆矩阵
inv_cov_matrix = np.linalg.inv(cov_matrix)
# 计算马氏距离
diffMat = dataSet - input_vector
distances = np.sqrt(np.sum(np.dot(diffMat, inv_cov_matrix) * diffMat, axis=1))
# 根据距离排序并获取索引 # 根据距离排序并获取索引
sorted_indices = distances.argsort() sorted_indices = distances.argsort()
# 选择距离最近的k个点 # 选择距离最近的k个点
k_nearest_labels = labels[sorted_indices[:k]] k_nearest_labels = labels[sorted_indices[:k]]
# 统计k个点中各类别的数量 # 统计k个点中各类别的数量
count = Counter(k_nearest_labels) count = Counter(k_nearest_labels)
# 返回数量最多的类别标签 # 返回数量最多的类别标签
return count.most_common(1)[0][0] return count.most_common(1)[0][0]
def load_dataset(directory): def load_dataset(directory):
"""加载数据集中的图像,并将其转换为特征向量和标签。""" """加载数据集中的图像,并将其转换为特征向量和标签。"""