generated from LufsX/Experiment-kNN
This commit is contained in:
+32
-4
@@ -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,7 +54,19 @@ def classify(input_vector, dataSet, labels, k=0):
|
||||
Returns:
|
||||
- int: 预测的分类标签。
|
||||
"""
|
||||
|
||||
# 计算输入向量与训练集中每个样本之间的欧氏距离
|
||||
distances = [np.sqrt(np.sum((x - input_vector) ** 2)) for x in dataSet]
|
||||
|
||||
# 获取距离最近的 k 个样本的索引
|
||||
k_indices = np.argsort(distances)[:k]
|
||||
|
||||
# 获取这 k 个样本的标签
|
||||
k_nearest_labels = [labels[i] for i in k_indices]
|
||||
|
||||
# 返回出现次数最多的标签
|
||||
from collections import Counter
|
||||
most_common = Counter(k_nearest_labels).most_common(1)
|
||||
return most_common[0][0]
|
||||
|
||||
# 这里也写自己的代码实现
|
||||
def load_dataset(directory):
|
||||
@@ -68,7 +80,19 @@ def load_dataset(directory):
|
||||
- np.array: 特征数据。
|
||||
- np.array: 标签数据。
|
||||
"""
|
||||
|
||||
data = []
|
||||
labels = []
|
||||
|
||||
for filename in os.listdir(directory):
|
||||
if filename.endswith(".txt"):
|
||||
label = int(filename.split('_')[0]) # 假设文件名格式为 "label_xxx.txt"
|
||||
with open(os.path.join(directory, filename), 'r') as f:
|
||||
img_str = f.read().strip()
|
||||
img_vector = np.array([int(pixel) for pixel in img_str]).reshape(1, -1)
|
||||
data.append(img_vector.flatten()) # 将图像向量展平
|
||||
labels.append(label)
|
||||
|
||||
return np.array(data), np.array(labels)
|
||||
|
||||
# 这里还写自己的代码实现
|
||||
def img_to_vector(filename):
|
||||
@@ -82,7 +106,11 @@ def img_to_vector(filename):
|
||||
Returns:
|
||||
- np.array: 二值图像向量。
|
||||
"""
|
||||
|
||||
|
||||
with open(filename, 'r') as f:
|
||||
img_str = f.read().strip()
|
||||
img_vector = np.array([int(pixel) for pixel in img_str]).reshape(1, -1)
|
||||
return img_vector.flatten()
|
||||
|
||||
if __name__ == "__main__":
|
||||
# 以下代码可用于测试,可自行随意修改
|
||||
|
||||
Reference in New Issue
Block a user