generated from LufsX/Challenge-kNN
This commit is contained in:
+20
-7
@@ -53,12 +53,15 @@ def classify0(inX, dataSet, labels, k=3):
|
||||
Args:
|
||||
- inX (numpy array): 输入待分类的样本。
|
||||
- dataSet (numpy array): 训练数据集。
|
||||
- labels (list or numpy array): 训练集对应的标签。
|
||||
- labels (numpy array): 训练集对应的标签。
|
||||
- k (int): KNN 算法参数,默认值为3。
|
||||
|
||||
Returns:
|
||||
- int: 预测的分类标签。
|
||||
"""
|
||||
# 确保 labels 是 numpy 数组
|
||||
labels = np.array(labels)
|
||||
|
||||
# 计算待分类样本与训练集中每个样本之间的距离
|
||||
distances = [euclidean_distance(inX, x) for x in dataSet]
|
||||
|
||||
@@ -67,13 +70,13 @@ def classify0(inX, dataSet, labels, k=3):
|
||||
k_nearest_indices = sorted_indices[:k]
|
||||
|
||||
# 获取k个最近样本的标签
|
||||
k_nearest_labels = [labels[i] for i in k_nearest_indices]
|
||||
k_nearest_labels = labels[k_nearest_indices]
|
||||
|
||||
# 统计每个标签出现的次数,并返回出现次数最多的标签
|
||||
label_counts = np.bincount(k_nearest_labels)
|
||||
predicted_label = np.argmax(label_counts)
|
||||
# 使用 np.unique 和 np.bincount 的一个更健壮的方法来找到出现次数最多的标签
|
||||
unique_labels, counts = np.unique(k_nearest_labels, return_counts=True)
|
||||
most_common_label = unique_labels[np.argmax(counts)]
|
||||
|
||||
return predicted_label
|
||||
return int(most_common_label) # 确保返回的是整数
|
||||
|
||||
def load_data(file_path):
|
||||
"""
|
||||
@@ -87,10 +90,20 @@ def load_data(file_path):
|
||||
if __name__ == "__main__":
|
||||
# 测试代码
|
||||
train_file = "datingTrainSet2.tsv"
|
||||
test_file = "datingTestSet2.tsv" # 假设有一个测试文件用于验证,虽然题目没明确要求
|
||||
test_file = "datingTestSet2.tsv" # 假设有一个测试文件用于验证
|
||||
|
||||
# 加载训练数据和测试数据
|
||||
train_data, train_labels = load_data(train_file)
|
||||
test_data, test_labels = load_data(test_file) # 取消注释以测试整个测试集
|
||||
|
||||
# 测试 classify0 函数
|
||||
sample = [65915, 3.868359, 0.128078] # 示例样本
|
||||
predicted_label = classify0(sample, train_data, train_labels)
|
||||
print(f"Predicted label for sample {sample}: {predicted_label}")
|
||||
|
||||
# 测试整个测试集(可选)
|
||||
accuracy = np.mean([classify0(test_data[i], train_data, train_labels) == test_labels[i] for i in range(len(test_data))])
|
||||
print(f"Accuracy on test set: {accuracy}")
|
||||
# test_data, test_labels = load_data(test_file) # 如果需要测试,可以取消注释并添加相应的测试代码
|
||||
|
||||
# 测试 classify0 函数
|
||||
|
||||
Reference in New Issue
Block a user