generated from LufsX/Challenge-kNN
This commit is contained in:
+21
-29
@@ -46,6 +46,15 @@ from collections import Counter
|
||||
def classify0(inX, dataSet, labels, k=1):
|
||||
"""
|
||||
KNN 分类算法。
|
||||
|
||||
Args:
|
||||
- inX (numpy array): 输入待分类的样本。
|
||||
- dataSet (numpy array): 训练数据集。
|
||||
- labels (list or numpy array): 训练集对应的标签。
|
||||
- k (int): KNN 算法参数,默认为3。
|
||||
|
||||
Returns:
|
||||
- int: 预测的分类标签。
|
||||
"""
|
||||
# 计算距离
|
||||
diffMat = inX - dataSet
|
||||
@@ -55,10 +64,15 @@ def classify0(inX, dataSet, labels, k=1):
|
||||
|
||||
# 排序并选取前k个最小距离
|
||||
sortedDistIndices = distances.argsort()
|
||||
classCount = Counter(labels[sortedDistIndices[:k]])
|
||||
classCount = {}
|
||||
|
||||
for i in range(k):
|
||||
voteIlabel = labels[sortedDistIndices[i]]
|
||||
classCount[voteIlabel] = classCount.get(voteIlabel, 0) + 1
|
||||
|
||||
# 返回出现频率最高的类别
|
||||
return classCount.most_common(1)[0][0]
|
||||
sortedClassCount = sorted(classCount.items(), key=lambda x: x[1], reverse=True)
|
||||
return sortedClassCount[0][0]
|
||||
|
||||
def load_data(file_path):
|
||||
"""
|
||||
@@ -69,35 +83,13 @@ def load_data(file_path):
|
||||
labels = data[:, -1].astype(int)
|
||||
return features, labels
|
||||
|
||||
def normalize_features(features):
|
||||
"""
|
||||
特征预处理,包括归一化。
|
||||
"""
|
||||
min_vals = features.min(axis=0)
|
||||
max_vals = features.max(axis=0)
|
||||
ranges = max_vals - min_vals
|
||||
m = features.shape[0]
|
||||
norm_features = features - np.tile(min_vals, (m, 1))
|
||||
norm_features = norm_features / np.tile(ranges, (m, 1))
|
||||
return norm_features
|
||||
|
||||
if __name__ == "__main__":
|
||||
# 以下代码可用于测试,可自行随意修改
|
||||
train_file = "datingTrainSet2.tsv"
|
||||
|
||||
train_data, train_labels = load_data(train_file)
|
||||
train_data_normalized = normalize_features(train_data)
|
||||
|
||||
# 选择几个有代表性的测试数据点
|
||||
test_points = [
|
||||
[26052, 1.441871, 0.805124], # 实际标签是 1
|
||||
[38344, 1.669788, 0.134296], # 实际标签是 1
|
||||
[28488, 10.528555, 1.304844], # 实际标签是 3
|
||||
[22620, 5.297865, 0.638306], # 实际标签是 2
|
||||
[28567, 9.968648, 0.731232], # 实际标签是 3
|
||||
[41611, 0.230453, 1.151996] # 实际标签是 1
|
||||
]
|
||||
|
||||
for point in test_points:
|
||||
normalized_point = normalize_features(np.array([point]))[0]
|
||||
predicted_label = classify0(normalized_point, train_data_normalized, train_labels)
|
||||
print(f"测试数据 {point} 预测标签: {predicted_label}")
|
||||
# 测试数据点
|
||||
test_point = np.array([65915, 3.868359, 0.128078])
|
||||
predicted_label = classify0(test_point, train_data, train_labels)
|
||||
print("预测的分类标签是:", predicted_label)
|
||||
Reference in New Issue
Block a user