generated from LufsX/Challenge-kNN
This commit is contained in:
+22
-17
@@ -38,30 +38,35 @@ name = "潘宇豪"
|
||||
"""
|
||||
|
||||
|
||||
def classify0(inX, dataSet, labels, k):
|
||||
def classify0(inX, dataSet, labels, k=4):
|
||||
"""
|
||||
KNN classification using Mahalanobis distance for fast computation.
|
||||
inX: The input sample to classify
|
||||
dataSet: The training data
|
||||
labels: The corresponding labels for the training data
|
||||
k: The number of nearest neighbors to consider
|
||||
KNN 分类算法,使用马氏距离,并避免显式循环。
|
||||
|
||||
参数:
|
||||
- inX (numpy array): 输入待分类的样本。
|
||||
- dataSet (numpy array): 训练数据集。
|
||||
- labels (list or numpy array): 训练集对应的标签。
|
||||
- k (int): 使用的邻居数量。
|
||||
|
||||
返回值:
|
||||
- int: 预测的分类标签。
|
||||
"""
|
||||
# Calculate covariance matrix and its inverse from the dataset
|
||||
cov_matrix = np.cov(dataSet.T)
|
||||
# 计算训练数据集的协方差矩阵和它的逆矩阵
|
||||
cov_matrix = np.cov(dataSet, rowvar=False)
|
||||
inv_cov_matrix = inv(cov_matrix)
|
||||
|
||||
# Compute the Mahalanobis distance between inX and all points in the dataset
|
||||
diff = dataSet - inX
|
||||
distances = np.sqrt(np.sum(np.dot(diff, inv_cov_matrix) * diff, axis=1))
|
||||
# 计算马氏距离
|
||||
diffMat = dataSet - inX
|
||||
distances = np.sqrt(np.sum(np.dot(diffMat, inv_cov_matrix) * diffMat, axis=1))
|
||||
|
||||
# Sort by distance and return the indices of the k nearest neighbors
|
||||
sorted_indices = np.argsort(distances)
|
||||
# 对距离进行排序并找到最近的k个邻居
|
||||
sortedDistIndices = np.argsort(distances)[:k] # 直接选择前k个最近的索引
|
||||
|
||||
# Get the labels of the k nearest neighbors
|
||||
k_nearest_labels = [labels[i] for i in sorted_indices[:k]]
|
||||
# 获取这k个邻居的标签
|
||||
k_nearest_labels = labels[sortedDistIndices]
|
||||
|
||||
# Return the most common label among the k nearest neighbors
|
||||
most_common_label = Counter(k_nearest_labels).most_common(1)[0][0]
|
||||
# 使用np.bincount计算每个标签的出现次数,并返回出现次数最多的标签
|
||||
most_common_label = np.bincount(k_nearest_labels).argmax()
|
||||
|
||||
return most_common_label
|
||||
|
||||
|
||||
Reference in New Issue
Block a user