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.
|
KNN 分类算法,使用马氏距离,并避免显式循环。
|
||||||
inX: The input sample to classify
|
|
||||||
dataSet: The training data
|
参数:
|
||||||
labels: The corresponding labels for the training data
|
- inX (numpy array): 输入待分类的样本。
|
||||||
k: The number of nearest neighbors to consider
|
- 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)
|
inv_cov_matrix = inv(cov_matrix)
|
||||||
|
|
||||||
# Compute the Mahalanobis distance between inX and all points in the dataset
|
# 计算马氏距离
|
||||||
diff = dataSet - inX
|
diffMat = dataSet - inX
|
||||||
distances = np.sqrt(np.sum(np.dot(diff, inv_cov_matrix) * diff, axis=1))
|
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
|
# 对距离进行排序并找到最近的k个邻居
|
||||||
sorted_indices = np.argsort(distances)
|
sortedDistIndices = np.argsort(distances)[:k] # 直接选择前k个最近的索引
|
||||||
|
|
||||||
# Get the labels of the k nearest neighbors
|
# 获取这k个邻居的标签
|
||||||
k_nearest_labels = [labels[i] for i in sorted_indices[:k]]
|
k_nearest_labels = labels[sortedDistIndices]
|
||||||
|
|
||||||
# Return the most common label among the k nearest neighbors
|
# 使用np.bincount计算每个标签的出现次数,并返回出现次数最多的标签
|
||||||
most_common_label = Counter(k_nearest_labels).most_common(1)[0][0]
|
most_common_label = np.bincount(k_nearest_labels).argmax()
|
||||||
|
|
||||||
return most_common_label
|
return most_common_label
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user