generated from LufsX/Experiment-kNN
This commit is contained in:
+26
-29
@@ -54,19 +54,19 @@ def classify(input_vector, dataSet, labels, k=3):
|
||||
Returns:
|
||||
- int: 预测的分类标签。
|
||||
"""
|
||||
# 计算输入向量与训练集中每个样本之间的欧氏距离
|
||||
distances = [np.sqrt(np.sum((x - input_vector) ** 2)) for x in dataSet]
|
||||
# 计算欧式距离
|
||||
distances = np.linalg.norm(dataSet - input_vector, axis=1)
|
||||
|
||||
# 获取距离最近的 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]
|
||||
# 找出出现次数最多的标签
|
||||
most_common = max(set(k_nearest_labels), key=k_nearest_labels.count)
|
||||
|
||||
return most_common
|
||||
|
||||
# 这里也写自己的代码实现
|
||||
def load_dataset(directory):
|
||||
@@ -80,28 +80,24 @@ def load_dataset(directory):
|
||||
- np.array: 特征数据。
|
||||
- np.array: 标签数据。
|
||||
"""
|
||||
data = []
|
||||
features = []
|
||||
labels = []
|
||||
directory="D:\\two"
|
||||
try:
|
||||
files = os.listdir(directory)
|
||||
print("Files in the directory:", files)
|
||||
except FileNotFoundError:
|
||||
print(f"The directory '{directory}' does not exist.")
|
||||
except PermissionError:
|
||||
print(f"You do not have permission to access the directory '{directory}'.")
|
||||
except Exception as e:
|
||||
print(f"An unexpected error occurred: {e}")
|
||||
|
||||
# 遍历文件夹中的所有文件
|
||||
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()) # 将图像向量展平
|
||||
if filename.endswith(".txt"): # 假设文件是 .txt 格式
|
||||
filepath = os.path.join(directory, filename)
|
||||
|
||||
# 假设文件名格式为 "数字_编号.txt"
|
||||
label = int(filename.split('_')[0])
|
||||
|
||||
# 加载文件中的二进制数据并转换为 1D 向量
|
||||
image_vector = img_to_vector(filepath)
|
||||
|
||||
features.append(image_vector)
|
||||
labels.append(label)
|
||||
|
||||
return np.array(data), np.array(labels)
|
||||
return np.array(features), np.array(labels)
|
||||
|
||||
# 这里还写自己的代码实现
|
||||
def img_to_vector(filename):
|
||||
@@ -116,10 +112,11 @@ def img_to_vector(filename):
|
||||
- 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()
|
||||
with open(filename) as file:
|
||||
lines = file.readlines()
|
||||
image_vector = np.array([int(char) for line in lines for char in line.strip()])
|
||||
|
||||
return image_vector
|
||||
|
||||
if __name__ == "__main__":
|
||||
# 以下代码可用于测试,可自行随意修改
|
||||
|
||||
Reference in New Issue
Block a user