generated from LufsX/Experiment-kNN
This commit is contained in:
+30
-3
@@ -25,8 +25,8 @@ import os
|
||||
"""
|
||||
请在这里填写学号和姓名,不填写即成绩无效。
|
||||
"""
|
||||
id = "202210423xxx"
|
||||
name = "test_name"
|
||||
id = "202210423209"
|
||||
name = "万子玉"
|
||||
|
||||
|
||||
"""
|
||||
@@ -41,7 +41,7 @@ name = "test_name"
|
||||
|
||||
|
||||
# 这里写自己的代码实现
|
||||
def classify(input_vector, dataSet, labels, k=0):
|
||||
def classify(input_vector, dataSet, labels, k=3):
|
||||
"""
|
||||
KNN 分类算法。
|
||||
|
||||
@@ -54,6 +54,22 @@ def classify(input_vector, dataSet, labels, k=0):
|
||||
Returns:
|
||||
- int: 预测的分类标签。
|
||||
"""
|
||||
dists = [distance.euclidean(input_vector, data) for data in dataSet]
|
||||
k_indices = np.argsort(dists)[:k]
|
||||
k_nearest_labels = [labels[i] for i in k_indices]
|
||||
|
||||
# 确保至少有一个近邻
|
||||
if not k_nearest_labels:
|
||||
raise ValueError("No neighbors found; possible causes: k is too small or all distances are the same.")
|
||||
|
||||
most_common = Counter(k_nearest_labels).most_common(1)
|
||||
|
||||
# 检查most_common是否为空
|
||||
if most_common:
|
||||
return most_common[0][0]
|
||||
else:
|
||||
# 如果为空,返回一个默认值或者抛出异常
|
||||
return None # 或者 raise ValueError("No common labels found")
|
||||
|
||||
|
||||
# 这里也写自己的代码实现
|
||||
@@ -68,6 +84,15 @@ def load_dataset(directory):
|
||||
- np.array: 特征数据。
|
||||
- np.array: 标签数据。
|
||||
"""
|
||||
data_list = []
|
||||
label_list = []
|
||||
for root, dirs, files in os.walk(directory):
|
||||
for file in files:
|
||||
file_path = os.path.join(root, file)
|
||||
vector = img_to_vector(file_path)
|
||||
data_list.append(vector)
|
||||
label_list.append(int(file.split('_')[0]))
|
||||
return np.array(data_list), np.array(label_list)
|
||||
|
||||
|
||||
# 这里还写自己的代码实现
|
||||
@@ -82,6 +107,8 @@ def img_to_vector(filename):
|
||||
Returns:
|
||||
- np.array: 二值图像向量。
|
||||
"""
|
||||
with open(filename, 'r') as f:
|
||||
return np.array([int(char) for char in f.read().strip()]).reshape(1, -1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
Reference in New Issue
Block a user