generated from LufsX/Challenge-kNN
This commit is contained in:
+17
-15
@@ -3,7 +3,6 @@ import numpy as np
|
|||||||
from collections import Counter
|
from collections import Counter
|
||||||
from scipy.spatial import distance
|
from scipy.spatial import distance
|
||||||
|
|
||||||
|
|
||||||
"""
|
"""
|
||||||
挑战说明:
|
挑战说明:
|
||||||
- 自行编写实现 KNN 分类算法。
|
- 自行编写实现 KNN 分类算法。
|
||||||
@@ -41,7 +40,7 @@ name = "程悦"
|
|||||||
|
|
||||||
|
|
||||||
# 这里写自己的代码实现
|
# 这里写自己的代码实现
|
||||||
def classify0(inX, dataSet, labels, inv_cov_matrix, k=9):
|
def classify0(inX, dataSet, labels, k=9):
|
||||||
"""
|
"""
|
||||||
KNN 分类算法。
|
KNN 分类算法。
|
||||||
|
|
||||||
@@ -54,19 +53,25 @@ def classify0(inX, dataSet, labels, inv_cov_matrix, k=9):
|
|||||||
Returns:
|
Returns:
|
||||||
- int: 预测的分类标签。
|
- int: 预测的分类标签。
|
||||||
"""
|
"""
|
||||||
|
# 计算协方差矩阵并求逆矩阵
|
||||||
|
cov_matrix = np.cov(dataSet, rowvar=False)
|
||||||
|
inv_cov_matrix = np.linalg.inv(cov_matrix)
|
||||||
|
|
||||||
# 计算输入样本与训练集样本的马氏距离
|
# 计算输入样本与训练集样本的马氏距离
|
||||||
distances = distance.cdist(dataSet, np.array([inX]), 'mahalanobis', VI=inv_cov_matrix).flatten()
|
distances = [distance.mahalanobis(inX, data_point, inv_cov_matrix) for data_point in dataSet]
|
||||||
|
|
||||||
# 按距离排序并选择前 k 个最近的邻居
|
# 按距离排序并选择前 k 个最近的邻居
|
||||||
k_indices = np.argpartition(distances, k)[:k]
|
k_indices = np.argsort(distances)[:k]
|
||||||
k_nearest_labels = labels[k_indices]
|
k_nearest_labels = [labels[i] for i in k_indices]
|
||||||
|
|
||||||
# 统计最近邻居中最多的标签
|
# 统计最近邻居中最多的标签
|
||||||
most_common_label = Counter(k_nearest_labels).most_common(1)[0][0]
|
label_counts = Counter(k_nearest_labels)
|
||||||
|
most_common_label = label_counts.most_common(1)[0][0]
|
||||||
|
|
||||||
return most_common_label
|
return most_common_label
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
def load_data(file_path):
|
def load_data(file_path):
|
||||||
"""
|
"""
|
||||||
加载 TSV 格式数据文件。
|
加载 TSV 格式数据文件。
|
||||||
@@ -83,20 +88,17 @@ if __name__ == "__main__":
|
|||||||
train_data, train_labels = load_data(train_file)
|
train_data, train_labels = load_data(train_file)
|
||||||
test_data, test_labels = load_data(test_file)
|
test_data, test_labels = load_data(test_file)
|
||||||
|
|
||||||
# 计算协方差矩阵并求逆矩阵
|
|
||||||
cov_matrix = np.cov(train_data, rowvar=False)
|
|
||||||
inv_cov_matrix = np.linalg.inv(cov_matrix)
|
|
||||||
|
|
||||||
# 测试 classify0 函数
|
# 测试 classify0 函数
|
||||||
test_sample = test_data[0] # 使用测试集中的第一个样本进行测试
|
test_sample = test_data[0] # 使用测试集中的第一个样本进行测试
|
||||||
predicted_label = classify0(test_sample, train_data, train_labels, inv_cov_matrix)
|
predicted_label = classify0(test_sample, train_data, train_labels)
|
||||||
print(f"Predicted label: {predicted_label}, Actual label: {test_labels[0]}")
|
print(f"Predicted label: {predicted_label}, Actual label: {test_labels[0]}")
|
||||||
|
|
||||||
# 遍历整个测试集来评估分类器的性能
|
# 遍历整个测试集来评估分类器的性能
|
||||||
correct_count = sum(
|
correct_count = 0
|
||||||
classify0(test_data[i], train_data, train_labels, inv_cov_matrix) == test_labels[i]
|
for i in range(len(test_data)):
|
||||||
for i in range(len(test_data))
|
predicted_label = classify0(test_data[i], train_data, train_labels)
|
||||||
)
|
if predicted_label == test_labels[i]:
|
||||||
|
correct_count += 1
|
||||||
accuracy = correct_count / len(test_data)
|
accuracy = correct_count / len(test_data)
|
||||||
print(f"Accuracy: {accuracy * 100:.2f}%")
|
print(f"Accuracy: {accuracy * 100:.2f}%")
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user