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

This commit is contained in:
2024-10-16 22:51:12 +08:00
parent bcd98ce08c
commit 1aae158e88
+49 -37
View File
@@ -1,61 +1,73 @@
import numpy as np
import os
"""
请在这里填写学号和姓名,不填写即成绩无效。
"""
id = "202210423124"
name = "刘子豪"
def classify0(input_vector, dataSet, labels, k=3):
def mahalanobis_distance(x1, x2, cov_inv, mean):
"""
KNN 分类算法。
计算两点之间的马氏距离。
Args:
x1 (numpy array): 第一个点。
x2 (numpy array): 第二个点。
cov_inv (numpy array): 协方差矩阵的逆矩阵。
mean (numpy array): 数据集的均值。
Returns:
float: 两点之间的马氏距离。
"""
delta = x1 - x2
dist = delta @ cov_inv @ delta.T
return np.sqrt(dist)
def classify0(inX, dataSet, labels, k=3):
"""
使用马氏距离的 KNN 分类算法。
Args:
- input_vector (numpy array): 输入待分类的样本。
- inX (numpy array): 输入待分类的样本。
- dataSet (numpy array): 训练数据集。
- labels (list or numpy array): 训练集对应的标签。
- k (int): kNN 算法参数,请**自行设置默认值**。
- k (int): kNN 算法参数,默认值为 3。
Returns:
- int: 预测的分类标签。
"""
# 计算输入向量与训练集中每个样本的欧氏距离
distances = np.linalg.norm(dataSet - input_vector, axis=1)
# 计算训练数据集的协方差矩阵和均值
cov_matrix = np.cov(dataSet, rowvar=False)
mean = np.mean(dataSet, axis=0)
cov_inv = np.linalg.inv(cov_matrix + np.eye(cov_matrix.shape[0]) * 1e-5) # 加上一个小的单位矩阵以避免奇异矩阵
# 计算待分类样本与训练集中每个样本的马氏距离
distances = np.array([mahalanobis_distance(inX, x, cov_inv, mean) for x in dataSet])
# 获取距离最近的 k 个样本的索引
sortedDistIndices = distances.argsort()[:k]
# 获取这些样本对应的标签
classCount = {}
for i in sortedDistIndices:
voteLabel = labels[i]
classCount[voteLabel] = classCount.get(voteLabel, 0) + 1
# 选择出现次数最多的标签作为预测标签
sortedClassCount = sorted(classCount.items(), key=lambda x: x[1], reverse=True)
return sortedClassCount[0][0]
# 按照距离从小到大排序并获取前k个距离最小的索引
sorted_indices = distances.argsort()[:k]
# 统计前k个最近邻的标签
nearest_labels = [labels[i] for i in sorted_indices]
# 返回出现次数最多的标签
predicted_label = max(set(nearest_labels), key=nearest_labels.count)
return predicted_label
def load_data(file_path):
"""
从 TSV 文件中加载数据集。
Args:
- file_path (str): TSV 文件路径。
Returns:
- np.array: 特征数据。
- np.array: 标签数据。
加载 TSV 格式数据文件。
"""
data = np.loadtxt(file_path, delimiter='\t')
data_set = data[:, :-1] # 假设最后一列是标签
data = np.loadtxt(file_path, delimiter="\t")
features = data[:, :-1]
labels = data[:, -1].astype(int)
return data_set, labels
return features, labels
if __name__ == "__main__":
# 以下代码可用于测试,可自行随意修改
train_file = "datingTrainSet2.tsv"
train_data, train_labels = load_data(train_file)
# 示例测试样本,确保维度与训练数据一致
# 测试一个样本
test_sample = np.array([65915, 3.868359, 0.128078])
prediction = classify0(test_sample, train_data, train_labels)
print(f"预测的分类标签: {prediction}")
predicted_label = classify0(test_sample, train_data, train_labels)
print(f"The predicted label for the test sample is: {predicted_label}")