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

This commit is contained in:
2024-10-11 11:11:58 +08:00
parent cbda375486
commit 5f262d4a21
+26 -13
View File
@@ -1,6 +1,7 @@
# function.py # function.py
import numpy as np import numpy as np
from sklearn.preprocessing import StandardScaler
from numpy.linalg import inv
""" """
挑战说明: 挑战说明:
- 自行编写实现 KNN 分类算法。 - 自行编写实现 KNN 分类算法。
@@ -39,28 +40,38 @@ name = "吴俊煯"
# 这里写自己的代码实现 # 这里写自己的代码实现
def classify0(inX, dataSet, labels,k=4): def classify0(inX, dataSet, labels, k=4, cov_inv=None):
""" """
KNN 分类算法。 KNN 分类算法,使用马氏距离。
Args: Args:
- inX (numpy array): 输入待分类的样本。 - inX (numpy array): 输入待分类的样本(形状应为 (1, n))。
- dataSet (numpy array): 训练数据集。 - dataSet (numpy array): 训练数据集(形状应为 (m, n))。
- labels (list or numpy array): 训练集对应的标签。 - labels (numpy array): 训练集对应的标签。
- k (int): 选择最近邻的个数。
- cov_inv (numpy array): 训练数据协方差矩阵的逆(可选,如果未提供,则函数内部计算)。
Returns: Returns:
- int: 预测的分类标签。 - int: 预测的分类标签。
""" """
# 计算每个训练样本与待分类样本之间的欧氏距离 if cov_inv is None:
distances = [np.sqrt(np.sum((x_train - inX) ** 2)) for x_train in dataSet] # 计算训练数据的协方差矩阵并求逆
cov_matrix = np.cov(dataSet.T)
cov_inv = inv(cov_matrix)
# 按距离排序,并获取最近的 k 个邻居的索引 # 计算待分类样本与所有训练样本之间的马氏距离
k_indices = np.argsort(distances)[:k] # 注意:这里我们假设 inX 已经被适当地预处理(例如,通过 StandardScaler 归一化)
# 并且 dataSet 也是用相同的预处理步骤处理的
differences = dataSet - inX
mahalanobis_distances = np.sqrt(np.sum(differences @ cov_inv @ differences.T, axis=1))
# 获取这 k 个邻居的标签 # 按距离排序,并获取前 k 个训练样本的索引
k_nearest_labels = [labels[i] for i in k_indices] k_indices = np.argsort(mahalanobis_distances)[:k]
# 统计每个标签出现的次数,并找出出现次数最多的标签 # 获取前 k 个训练样本的标签
k_nearest_labels = labels[k_indices]
# 找到出现次数最多的标签
from collections import Counter from collections import Counter
most_common = Counter(k_nearest_labels).most_common(1) most_common = Counter(k_nearest_labels).most_common(1)
@@ -68,6 +79,8 @@ def classify0(inX, dataSet, labels,k=4):
return most_common[0][0] return most_common[0][0]
def load_data(file_path): def load_data(file_path):
""" """
加载 TSV 格式数据文件。 加载 TSV 格式数据文件。