generated from LufsX/Challenge-kNN
This commit is contained in:
+9
-10
@@ -1,6 +1,6 @@
|
||||
# function.py
|
||||
import numpy as np
|
||||
from numpy.linalg import inv
|
||||
from numpy.linalg import inv,dot
|
||||
|
||||
"""
|
||||
挑战说明:
|
||||
@@ -40,7 +40,7 @@ name = "潘宇豪"
|
||||
|
||||
def classify0(inX, dataSet, labels, k=3):
|
||||
"""
|
||||
KNN 分类算法,使用马氏距离,并对特定的第64次错误实例进行修正。
|
||||
KNN 分类算法。
|
||||
|
||||
参数:
|
||||
- inX (numpy array): 输入待分类的样本。
|
||||
@@ -51,26 +51,25 @@ def classify0(inX, dataSet, labels, k=3):
|
||||
返回值:
|
||||
- int: 预测的分类标签。
|
||||
"""
|
||||
# 特定实例的手动修正
|
||||
# 修正第64次测试错误,数据[5.56500e+03 9.73334e+00 9.77746e-01]被分类到3实际是2
|
||||
if np.allclose(inX, [5.56500e+03, 9.73334e+00, 9.77746e-01], atol=1e-2):
|
||||
return 2 # 返回正确分类
|
||||
|
||||
# 计算马氏距离
|
||||
# 计算均值和协方差的逆
|
||||
mean = np.mean(dataSet, axis=0)
|
||||
cov_inv = inv(np.cov(dataSet, rowvar=False))
|
||||
|
||||
# 计算每个样本与输入样本的马氏距离
|
||||
# 计算输入样本与每个训练样本之间的马氏距离
|
||||
diff = dataSet - inX
|
||||
distances = np.sqrt(np.einsum('ij,jk->i', diff, np.dot(cov_inv, diff.T)))
|
||||
|
||||
# 找到最近的k个邻居
|
||||
sortedDistIndices = np.argsort(distances)[:k]
|
||||
classCount = np.bincount(labels[sortedDistIndices].astype(int))
|
||||
nearest_labels = labels[sortedDistIndices]
|
||||
|
||||
# 使用np.bincount统计类别出现次数
|
||||
classCount = np.bincount(nearest_labels.astype(int))
|
||||
|
||||
# 返回出现次数最多的类别
|
||||
return np.argmax(classCount)
|
||||
|
||||
|
||||
def load_data(file_path):
|
||||
"""
|
||||
加载TSV格式的数据文件。
|
||||
|
||||
Reference in New Issue
Block a user