generated from LufsX/Experiment-kNN
This commit is contained in:
+8
-5
@@ -55,7 +55,7 @@ def classify(input_vector, dataSet, labels, k=3):
|
||||
- int: 预测的分类标签。
|
||||
"""
|
||||
"""
|
||||
欧式距离的 kNN 分类算法。
|
||||
使用欧式距离的 kNN 分类算法。
|
||||
"""
|
||||
# 计算欧式距离
|
||||
distances = np.linalg.norm(dataSet - input_vector, axis=1)
|
||||
@@ -70,8 +70,10 @@ def classify(input_vector, dataSet, labels, k=3):
|
||||
most_common = max(set(k_nearest_labels), key=k_nearest_labels.count)
|
||||
|
||||
return most_common
|
||||
|
||||
|
||||
|
||||
# 这里也写自己的代码实现
|
||||
|
||||
def load_dataset(directory):
|
||||
"""
|
||||
从文件夹中加载数据,若不自行正确实现,则无法通过评测,**不记录成绩**。
|
||||
@@ -83,8 +85,8 @@ def load_dataset(directory):
|
||||
- np.array: 特征数据。
|
||||
- np.array: 标签数据。
|
||||
"""
|
||||
features = []
|
||||
labels = []
|
||||
features = []
|
||||
labels = []
|
||||
|
||||
# 遍历文件夹中的所有文件
|
||||
for filename in os.listdir(directory):
|
||||
@@ -102,6 +104,7 @@ labels = []
|
||||
|
||||
return np.array(features), np.array(labels)
|
||||
|
||||
|
||||
# 这里还写自己的代码实现
|
||||
def img_to_vector(filename):
|
||||
"""
|
||||
@@ -114,7 +117,7 @@ def img_to_vector(filename):
|
||||
Returns:
|
||||
- np.array: 二值图像向量。
|
||||
"""
|
||||
with open(filename) as file:
|
||||
with open(filename) as file:
|
||||
lines = file.readlines()
|
||||
image_vector = np.array([int(char) for line in lines for char in line.strip()])
|
||||
|
||||
|
||||
Reference in New Issue
Block a user