generated from LufsX/Experiment-kNN
This commit is contained in:
+3
-36
@@ -47,52 +47,19 @@ from collections import Counter
|
||||
|
||||
|
||||
# 这里写自己的代码实现
|
||||
def classify(input_vector, dataSet, labels, k=3):
|
||||
def classify(input_vector, dataSet, labels, k=2):
|
||||
"""
|
||||
使用 KNN 算法对输入样本进行分类。
|
||||
|
||||
参数:
|
||||
- input_vector (numpy array): 输入待分类的样本(1xN)。
|
||||
- dataSet (numpy array): 训练数据集(MxN)。
|
||||
- input_vector (numpy array): 输入待分类的样本(1xN)。
|
||||
- dataSet (numpy array): 训练数据集(MxN)。
|
||||
- labels (list or numpy array): 训练集对应的标签。
|
||||
- k (int): kNN 算法参数,默认值为 3。
|
||||
|
||||
返回:
|
||||
- int: 预测的分类标签。
|
||||
"""
|
||||
# 在 classify 函数中实现权重投票
|
||||
distances = np.sum((input_vector - dataSet) ** 2, axis=1)
|
||||
sorted_indices = distances.argsort()
|
||||
k_nearest_distances = distances[sorted_indices[:k]]
|
||||
k_nearest_labels = labels[sorted_indices[:k]]
|
||||
|
||||
# 计算权重(距离的倒数)
|
||||
weights = 1 / k_nearest_distances
|
||||
# 归一化权重
|
||||
weights /= weights.sum()
|
||||
|
||||
# 计算加权投票
|
||||
weighted_votes = np.zeros((10,))
|
||||
for label, weight in zip(k_nearest_labels, weights):
|
||||
weighted_votes[label] += weight
|
||||
|
||||
return np.argmax(weighted_votes)
|
||||
|
||||
# 在 load_dataset 函数中添加特征缩放
|
||||
def load_dataset(directory):
|
||||
feature_list = []
|
||||
label_list = []
|
||||
for file in os.listdir(directory):
|
||||
file_path = os.path.join(directory, file)
|
||||
feature_vector = img_to_vector(file_path)
|
||||
feature_list.append(feature_vector)
|
||||
label_list.append(int(file.split('_')[0]))
|
||||
feature_matrix = np.array(feature_list)
|
||||
label_array = np.array(label_list)
|
||||
|
||||
# 特征缩放
|
||||
feature_matrix = feature_matrix / 255.0
|
||||
return feature_matrix, label_array
|
||||
# 计算输入向量与训练集之间的欧氏距离
|
||||
distances = np.sum((input_vector - dataSet) ** 2, axis=1) ** 0.5
|
||||
# 根据距离排序并获取索引
|
||||
|
||||
Reference in New Issue
Block a user