generated from LufsX/Challenge-kNN
This commit is contained in:
+7
-25
@@ -42,18 +42,6 @@ name = "李燕如"
|
||||
|
||||
# 这里写自己的代码实现
|
||||
def classify0(inX, dataSet, labels, k=5):
|
||||
"""
|
||||
KNN 分类算法。
|
||||
|
||||
Args:
|
||||
- inX (numpy array): 输入待分类的样本。
|
||||
- dataSet (numpy array): 训练数据集。
|
||||
- labels (list or numpy array): 训练集对应的标签。
|
||||
- k (int): kNN 算法参数。
|
||||
|
||||
Returns:
|
||||
- int: 预测的分类标签。
|
||||
"""
|
||||
# 数据标准化
|
||||
dataSet = (dataSet - np.mean(dataSet, axis=0)) / np.std(dataSet, axis=0)
|
||||
inX = (inX - np.mean(dataSet, axis=0)) / np.std(dataSet, axis=0)
|
||||
@@ -67,22 +55,16 @@ def classify0(inX, dataSet, labels, k=5):
|
||||
# 获取这些样本对应的标签
|
||||
k_nearest_labels = labels[k_indices]
|
||||
|
||||
# 统计每个类别出现的次数
|
||||
count = {}
|
||||
for label in k_nearest_labels:
|
||||
if label in count.keys():
|
||||
count[label] += 1
|
||||
else:
|
||||
count[label] = 1
|
||||
# 权重分配(距离的倒数)
|
||||
weights = 1 / distances[k_indices]
|
||||
weights /= np.sum(weights) # 归一化权重
|
||||
|
||||
# 找到出现次数最多的类别
|
||||
sorted_count = sorted(count.items(), key=lambda x: x[1], reverse=True)
|
||||
return sorted_count[0][0]
|
||||
# 加权投票
|
||||
prediction = np.argmax(np.bincount(k_nearest_labels, weights=weights))
|
||||
|
||||
return prediction
|
||||
|
||||
def load_data(file_path):
|
||||
"""
|
||||
加载 TSV 格式数据文件。
|
||||
"""
|
||||
data = np.loadtxt(file_path, delimiter="\t")
|
||||
features = data[:, :-1]
|
||||
labels = data[:, -1].astype(int)
|
||||
|
||||
Reference in New Issue
Block a user